package com.bigdata.schaduler.service;

import com.bigdata.schaduler.client.DolphinClient;
import com.bigdata.schaduler.domain.TaskInstanceQueryParam;
import com.bigdata.schaduler.util.PageInfo;
import org.apache.dolphinscheduler.common.enums.HttpMethod;
import org.apache.dolphinscheduler.dao.entity.ResponseTaskLog;
import org.apache.dolphinscheduler.dao.entity.TaskInstance;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

public class TaskInstanceService {
  private final DolphinClient dolphinClient;

  public TaskInstanceService(DolphinClient dolphinClient) {
    this.dolphinClient = dolphinClient;
  }

  public String getProcessInstanceUri(Long projectCode) {
    return "projects/" + projectCode + "/task-instances";
  }

  public PageInfo<TaskInstance> selectPageList(Long projectCode, TaskInstanceQueryParam param) {
    String uri = getProcessInstanceUri(projectCode);
    return dolphinClient.requestFormData(HttpMethod.GET, uri, param, PageInfo.class);
  }

  public void savePoint(Long projectCode, Long instanceId) {
    String uri = getProcessInstanceUri(projectCode) + "/" + instanceId + "/savepoint";
    dolphinClient.requestFormData(HttpMethod.POST, uri, null, Void.class);
  }

  public void forceSuccess(Long projectCode, Long instanceId) {
    String uri = getProcessInstanceUri(projectCode) + "/" + instanceId + "/force-success";
    dolphinClient.requestFormData(HttpMethod.POST, uri, null, Void.class);
  }

  public void stop(Long projectCode, Long instanceId) {
    String uri = getProcessInstanceUri(projectCode) + "/" + instanceId + "/stop";
    dolphinClient.requestFormData(HttpMethod.POST, uri, null, Void.class);
  }

  public ResponseTaskLog getLog(Long instanceId, int skipNum, int limit) {
    String uri = "/log/detail";
    MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
    params.add("taskInstanceId", instanceId);
    params.add("skipLineNum", skipNum);
    params.add("limit", limit);
    return dolphinClient.requestFormData(HttpMethod.GET, uri, params, ResponseTaskLog.class);
  }
}
